//
//  VersionCheckController.m
//  AntsExpress
//
//  Created by slccper on 16/1/15.
//  Copyright © 2016年 slccper. All rights reserved.
//

#import "VersionCheckController.h"

#import "clsOtherFun.h"
#import "clsAntsService.h"
#import "MainViewController.h"
#import "AppDelegate.h"
#import "CustomNavigation.h"
#import "UIAlertView+Blocks.h"
#import "clsFileFun.h"
@interface VersionCheckController ()<clsAntsServiceDelegate>
{
    NSTimer *timer;
    UIButton *btn;
    NSString *WebUrl;
}
@property (nonatomic,strong)clsAntsService *ants;
@property (nonatomic,retain)UIImageView *bgview;
@end

@implementation VersionCheckController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.ants = [[clsAntsService alloc]init];
    self.ants.delegate=self;
    self.view.backgroundColor = [UIColor colorWithRed:248/255.0f green:248/255.0f blue:193/255.0f alpha:1];
    [self getWebData];
    self.bgview = [[UIImageView alloc]initWithFrame:self.view.frame];
    self.bgview.contentMode = UIViewContentModeScaleAspectFit;
    self.bgview.image=[UIImage imageNamed:@"Default-568h@2x.png"];
     btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"跳過" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor ] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(GetVersionAction) forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(ScreenWidth-100, 20, 70, 30)];
    btn.backgroundColor  = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    btn.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0].CGColor;
    btn.layer.borderWidth=1;
    btn.layer.cornerRadius = 6;
    [self.view addSubview:self.bgview];
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)getWebData
{
    if ([clsOtherFun CheckNetworkStatus:YES]) {
        //        [clsOtherFun showLoadingView:@"正在獲取數據"];
        [self.ants DeviceLoadImg:^(NSDictionary *dic) {
            NSString *status = [dic objectForKey:@"status"];
            if ([status integerValue]==200) {
                [clsOtherFun setIsFirstRun];
                NSArray *data = [dic objectForKey:@"data"];
                if(data.count>0){
                    NSArray *arr = [[[data firstObject] objectForKey:@"Url"]componentsSeparatedByString:@"/"];
                    NSString *photoname = [arr lastObject];
                    NSData *dashowdatata;
                    NSString *path =[clsFileFun getFilePath:[clsFileFun getShowImage] :photoname];
                    [[NSFileManager defaultManager] createDirectoryAtPath:[clsFileFun getShowImage] withIntermediateDirectories:YES attributes:nil error:nil];
                    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
                        NSURL *url = [NSURL URLWithString:[[data firstObject] objectForKey:@"Url"]];
                        dashowdatata= [NSData dataWithContentsOfURL:url];
                        [clsFileFun saveFile:path :dashowdatata];
                    }else{
                        NSString *path = [clsFileFun getFilePath:[clsFileFun getShowImage] :photoname];
                        dashowdatata = [clsFileFun loadFile:path];
                    }
                    WebUrl = [[data firstObject] objectForKey:@"WebUrl"];
                    UIImage *image = [UIImage imageWithData:dashowdatata];
                    self.bgview.image =image;
                    self.bgview.userInteractionEnabled = YES;
                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImage:)];
                    [self.bgview addGestureRecognizer:tap];
                    [self.view addSubview:btn];
                    NSInteger time = [[[data firstObject]objectForKey:@"ShowTime"] integerValue];
                    if (time==0) {
                        time=3;
                    }
                    timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(GetVersionAction) userInfo:nil repeats:NO];
                }else{
                    [self.ants GetAppNewVersion];
                }
                }else{
                [self.ants GetAppNewVersion];
            }
        }];;
    }
}
-(void)GetVersionAction
{
    [timer invalidate];
    timer = nil;
    [self.ants GetAppNewVersion];
}
-(void)getAntsDataFail:(NSInteger)type
{
    if (type==Ants_GetAppNewVersion) {
        [clsOtherFun ShowMsg:@"網絡連接失敗！"];
    }else{
        MainViewController *main = [[MainViewController alloc]init];
        //    main.bannerList =_bannerList;
        CustomNavigation *nav = [[CustomNavigation alloc]initWithRootViewController:main];
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        app.window.rootViewController = nav;
    }
}
-(void)getAntsDataSuccess:(NSInteger)type :(NSMutableDictionary *)pDictionary
{
    if (type==Ants_GetAppNewVersion) {
        NSDictionary *dic = [pDictionary objectForKey:@"data"];
        NSString *status = [dic objectForKey:@"status"];
        if ([status integerValue]==200) {
            if ([[dic objectForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *data = [dic objectForKey:@"data"];
                NSString *valid = [data objectForKey:@"isValid"];
                NSString *mark = [data objectForKey:@"mark"];
                
                if ([valid integerValue]==1) {
                    RIButtonItem *cancel = [RIButtonItem itemWithLabel:@"去看看" action:^{
                        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[data objectForKey:@"downloadUrl"]]];
                        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(exitAction) userInfo:nil repeats:NO];
                    }];
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:mark cancelButtonItem:cancel otherButtonItems:nil, nil];
                    [alert show];
                }else{
                    RIButtonItem *cancel = [RIButtonItem itemWithLabel:@"去看看" action:^{
                        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[data objectForKey:@"downloadUrl"]]];
                        
                    }];
                    RIButtonItem *sure = [RIButtonItem itemWithLabel:@"取消" action:^{
                        
                    }];
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:mark cancelButtonItem:cancel otherButtonItems:sure, nil];
                    [alert show];
                    [self.ants GetSlideBox];
                }
            }else{
                [self.ants GetSlideBox];
            }
        }
        
    }else{
        self.ants.delegate=nil;
        self.ants=nil;
        NSMutableArray *_bannerList = [pDictionary objectForKey:@"data"];
        MainViewController *main = [[MainViewController alloc]init];
        main.bannerList =_bannerList;
        CustomNavigation *nav = [[CustomNavigation alloc]initWithRootViewController:main];
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        app.window.rootViewController = nav;
    }
}
-(void)exitAction
{
    exit(0);
}
-(void)dealloc
{
    
}
- (void)showImage:(id)sender
{
    if(![WebUrl isKindOfClass:[NSNull class]]){
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:WebUrl]];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
